#读取xml练习

import xml.dom.minidom
import os
from xml.parsers.expat import ParserCreate

ROOT_URL = os.path.split(__file__)[0]

class XmlElement():
    def __init__(self,nodeName,text,attr:dict,parent=None):
        self.nodeName = nodeName
        self.text = text
        self.attr = attr if attr else {}
        self.children = {}


class ExpatXmlParser(object):
    def __init__(self,xmlStr):
        self.xmlStr = xmlStr
        self._curNodeName = ""
        self._curNodeText = ""
        self._curNodeAttr = {}        
        self._rootNode = ""
        self.rootNode = None
        self._endFlagDict = {}
        self.__parse()

    def __parse(self):
        p = ParserCreate()
        p.StartElementHandler = self.start_element
        p.EndElementHandler = self.end_element
        p.CharacterDataHandler = self.char_data
        p.Parse(self.xmlStr) #开始解析xml,依次执行上面的函数
        self.__p = p    

    def start_element(self,nodeName,attrDict):  # <model>python</model> 读取 <model>  时执行该函数
        print('----start nodeName,attrDict=',nodeName,attrDict)
        if self._rootNode =="":
            self._rootNode = nodeName
            self.rootNode = XmlElement(nodeName,"",attrDict)

        
        #isHasParent = self._curNode != None 


        if self._curNodeName != nodeName:
            self._curNodeName = nodeName
            self._curNodeText = ""
            self._curNode = XmlElement(nodeName,'',attrDict)
            



    def end_element(self,nodeName): # <model>python</model> 读取 </model> 时执行该函数
        print("====end nodeName=",nodeName)

    #当字符串比较长的时候该函数可能会被多次调用，需要保存,然后在EndElementHandler里面合并
    def char_data(self,text): # <model>python</model> 读取python时执行该函数
        print("++++chardata text=",text)

xmlUrl = os.path.join(ROOT_URL,'Main.xml') # abc Main

with open(xmlUrl,'r',encoding='utf8') as f:
    xmlStr = f.read()
#print(xmlStr)
parser = ExpatXmlParser(xmlStr)


